console.log($event);
const { type, params, instanceName, data } = $event;
const prefix = this.pageObj.getVariables().find(v => v.name === 'environmentType')?.value || '';
const gis = this.getApiPage().getApiWidgetByAliasName('三维组件');
const queryManage = this.pageObj.getApiWidgetByAliasName('queryManage')?.widgetObj;
const publicParams = this.getApiPage().getVariables().find(v => v.name === 'panel_type');
const searchValue = this.getApiPage().getVariables().find(v => v.name === 'event_search')?.value;
const whether_process = this.getApiPage().getVariables().find(v => v.name === 'whether_process')?.value
const emergency_cont = this.pageObj.getApiWidgetsByClassName('emergency_context')
const resType = this.pageObj.getApiWidgetByAliasName('resType')?.widgetObj;
resType._option.defaultKey = 'member_linkage'
resType.render()
function basicsFetch(url) {
    const headers = { "Content-type": "application/json" };
    return fetch(`/${prefix}Basics/basics-main/${url}`, { headers })
}
const requestPost = (url, body) => {
    const options = {
        method: 'POST',
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body)
    };
    return fetch(url, options).then(res => res.json())
};
const requestGet = (url, body) => {
    const headers = { "Content-type": "application/json" };
    return fetch(url, { headers }).then(res => res.json())
};
const openDetail = (data) => {
    const $playback = this.getApiPage().getApiWidgetByAliasName('playback');
    const detail = this.getApiPage().getApiWidgetsByClassName('detail');
    const modalBtns = this.getApiPage().getApiWidgetByAliasName('modal-btns');
    const { eventDetails, areaId } = data;
    this.pageObj.setVariables([{ 'name': 'areaId', 'value': areaId }]);
    const setFormSelect = this.getApiPage().getApiWidgetByAliasName('judge-content').widgetObj;
    const btns = this.pageObj.getApiWidgetByAliasName('modal-btns')?.widgetObj;
    setFormSelect.areaId = areaId
    detail.forEach(v => v.showWidget())
    emergency_cont.forEach(v => v.hideWidget())
    gis.widgetObj.setIconPosition({ right: 420, top: 100 });
    gis.widgetObj.setModalPosition({ right: 815, bottom: 20 });
    $playback.hideWidget();
    gis.widgetObj.sullivan.close();
    const $form = this.getApiPage().getApiWidgetByAliasName('judge-content');
    const $img = this.getApiPage().getApiWidgetByAliasName('detail-img');

    data.eventPoint = data.xCoordinate + '，' + data.yCoordinate + '，' + data.zCoordinate;
    let info = {}
    if (eventDetails) {
        info = JSON.parse(eventDetails);
    }
    const formData = {
        ...data,
        thumbnailPath: info.thumbnailPath,
        jpbPath: info.jpbPath,
    };

    if (formData.whetherProcess !== 1) {
        modalBtns.showWidget()
    }
    if (+formData.disableFlag === 2) {
        btns?.renderDispose();
    } else {
        btns?.renderEvent();
    }
    // 详情时隐藏上传功能
    $form.widgetObj._option.config.forEach(v => {
        if (v.type == 'upload') {
            v.visible = true
        }
        if (v.dataIndex == 'sourceDeviceId') {
            v.visible = true
        }
    });

    try {

        $form.widgetObj._option.dataSource = formData;
        $form.widgetObj._option.isDetail = true;
        $form.widgetObj.render();
    } catch (e) {
        console.error(e)
    }
    if (Object.keys(info).length !== 0) {
        if (info.thumbnailPath) {
            const srcArr = info?.thumbnailPath.split(',').map(v => ({ src: v }));
            $img.widgetObj.setData([{ data: srcArr }]);
            $img.widgetObj.render()
        } else {
            $img.widgetObj.setData([{ data: [] }]);
            $img.widgetObj.render();
        }
    } else {
        $img.widgetObj.setData([{ data: [] }]);
        $img.widgetObj.render();
    }
}
// 获取当前演练人员列表
const requestPerson = (eventId) => (
    requestGet(`/${prefix}SummaryAssessmentSV/emergencyRecord/recordFilterCriteria?eventId=${eventId}`).then(({ success, result }) => {
        console.log(this, { success, result });
        if (success && result && Array.isArray(result.personList)) return result.personList.map(item => ({
            name: item, value: item,
        }))
    })
)
const openRecord = () => {
    const timeline = this.getApiPage().getApiWidgetByAliasName('timelineVertical');
    const formRecord = this.getApiPage().getApiWidgetByAliasName('formRecord');
    const summary = this.getApiPage().getApiWidgetByAliasName('summary');
    const { data } = params;

    summary.hideWidget();
    timeline.showWidget();
    formRecord.showWidget();
    openDetail(data);

    // 成员
    requestPerson(data.id).then((result) => {
        if (result) {
            formRecord.widgetObj.asyncSelectOptions('personName', result);
        }
    })

    if (timeline && timeline.widgetObj) {
        const { setUpdateStatus } = timeline.widgetObj;

        if (setUpdateStatus) setUpdateStatus(data.whetherProcess !== 1);
        // if (setVariable) setVariable('timeline_event_id', data.id);
        // if (setVariable) setVariable('eventId', data.id);
        requestPost(`/${prefix}SummaryAssessmentSV/emergencyRecord/planHandleProcessDetailByReq`, { eventId: data.id }).then(({ result, success }) => {
            if (success && Array.isArray(result)) {
                timeline.widgetObj.dataSource = result;
                timeline.widgetObj.render();
            }
            console.log('事件记录： =》 ', { result, success })
        })
    }
}

if (type === 'page') {
    const options = {
        pageNum: params,
        pageSize: 10,
        eventTitle: search,
        projectCode: data.projectCode,
        whetherProcess: whether_process
    };

    if (typeof search === 'string') {
        options.eventTitle = search
    } else {
        options.eventTitle = $(search).val();
    }

    if (+publicParams?.value === 1) {
        options.occurrencePlace = instanceName
    } else if (+publicParams?.value === 2) {
        options.eventType = instanceName
    } else if (+publicParams?.value === 3) {
        options.eventGrade = instanceName
    } else {
        options.occurrencePlace = instanceName
    }

    console.log('pagetion: => ', options, data);
    queryManage.queryList(options, $event).then(({ success, result }) => {
        console.log({ success, result });
        if (success) {
            this.widgetObj.tree.pannelRerender(data.uniqueKey, { dataSource: result })
        }
    })
} else if (type === 'operation') {
    const { operation, data } = params;
    const eventParams = JSON.stringify({ eventId: data.id, ...data });

    // 周边资源变化
    this.pageObj.setVariables([{ name: 'event_record_id', value: data.id }]);
    this.getApiPage().setVariables([{ name: 'event_record_type', value: 5 }]);

    switch (operation.type) {
        case '处置': {
            window.parent.postMessage({ type: 'nav/style', pageName: '处置' }, document.referrer);
            var authTokenVar = this.getApiPage().getVariables().find(x => x.name == "AuthToken");
            this.getApiPage().navigateStage('833630884086153216', [
                { name: 'screen_params', value: eventParams },
                { name: 'AuthToken', value: authTokenVar.value },
                { name: 'environmentType', value: prefix },
            ])
        }
            break;
        case '疏散':

            break;
        case '总结': {
            const timeline = this.getApiPage().getApiWidgetByAliasName('timelineVertical');
            const summary = this.getApiPage().getApiWidgetByAliasName('summary').widgetObj;
            timeline.hideWidget();
            this.pageObj.setVariables([{ name: 'timeline_event_id', value: data.id }]);
            summary.show();
            $('#summary .file-box').text(summary.fileName);
            openDetail(data)
            //   window.parent.postMessage({ type: 'nav/style', pageName: '总结' }, document.referrer);
        }
            break;
        case '记录': {
            openRecord(data);
            // window.parent.postMessage({ type: 'nav/style', pageName: '记录' }, document.referrer);
        }
            break;
        case 'whetherProcess': {
            if (data.whetherProcess == 0) {
                fetch(`/${prefix}Event/event/receivingAlarm/${data.id}`)
            }
            gis.widgetObj.setIconPosition({ right: 420, top: 100 });
            gis.widgetObj.setModalPosition({ right: 815, bottom: 20 });
            if (data.xCoordinate && data.yCoordinate && data.zCoordinate) {
                gis.widgetObj.gisMap.setEvent(data)
            } else {
                window.layer?.msg('该事件无位置信息')
            }
            const detail = this.getApiPage().getApiWidgetsByClassName('detail');
            const modalBtns = this.getApiPage().getApiWidgetByAliasName('modal-btns');
            const { eventDetails, areaId } = data;
            this.pageObj.setVariables([{ 'name': 'areaId', 'value': areaId }]);
            const setFormSelect = this.getApiPage().getApiWidgetByAliasName('judge-content')?.widgetObj;
            const btns = this.pageObj.getApiWidgetByAliasName('modal-btns')?.widgetObj;
            setFormSelect.areaId = areaId
            detail.forEach(v => v.showWidget())
            emergency_cont.forEach(v => v.hideWidget())
            const $form = this.getApiPage().getApiWidgetByAliasName('judge-content');
            const $img = this.getApiPage().getApiWidgetByAliasName('detail-img');
            data.eventPoint = data.xCoordinate + '，' + data.yCoordinate + '，' + data.zCoordinate;
            let info = {}
            if (eventDetails) {
                info = JSON.parse(eventDetails);
            }
            const formData = {
                ...data,
                thumbnailPath: info.thumbnailPath,
                jpbPath: info.jpbPath,
            };

            if (formData.whetherProcess !== 1) {
                modalBtns.showWidget()
            }

            // 详情时隐藏上传功能
            $form.widgetObj._option.config.forEach(v => {
                if (v.type == 'upload') {
                    v.visible = true
                }
                if (v.dataIndex == 'sourceDeviceId') {
                    v.visible = true
                }
            });

            try {
                $form.widgetObj._option.dataSource = formData;
                $form.widgetObj._option.isDetail = true;
                $form.widgetObj.render();
            } catch (e) {
                console.error(e)
            }

            const $playback = this.getApiPage().getApiWidgetByAliasName('playback');

            if (+formData.disableFlag === 2) {
                btns?.renderDispose();
            } else {
                btns?.renderEvent();
            }
            // const info = JSON.parse(eventDetails)
            if (Object.keys(info).length !== 0) {
                if (info.thumbnailPath) {
                    const srcArr = info?.thumbnailPath.split(',').map(v => ({ src: v }));
                    $img.widgetObj.setData([{ data: srcArr }]);
                    $img.widgetObj.render()
                } else {
                    $img.widgetObj.setData([{ data: [] }]);
                    $img.widgetObj.render();
                }

                if (info?.jpbPath) {
                    // 打开回放
                    $playback.widgetObj.setData([{ data: info?.jpbPath }]);
                    $playback.showWidget();
                    $playback.widgetObj.render();
                } else {
                    $playback.hideWidget();
                    window.layer.msg('暂无录像回放')
                }
            } else {
                $img.widgetObj.setData([{ data: [] }]);
                $img.widgetObj.render();

                $playback.hideWidget();
                window.layer.msg('暂无录像回放')
            }

            if (data.sourceDeviceId) {
                gis.widgetObj.addCameraContext(data.sourceDeviceId);

                // 打开实时视频
                basicsFetch(`/system/equipmentObject/listDetailByEquipmentCode?equipmentCode=${data.sourceDeviceId}`)
                    .then(res => res.json())
                    .then(json => {
                        if (json?.success && json.result) {
                            const { rows } = json.result;
                            const data = rows[0]?.equipmentConfig?.gbVideoConfig;
                            var host = this.getApiPage().getVariables().find(x => x.name == "stream_url").value;
                            gis.widgetObj.sullivan.close();
                            if (data && data.sipUser && data.videoChannelId) {
                                gis.widgetObj.sullivan.initial();
                                gis.widgetObj.sullivan.addPlayer(`${host}/api/v1/stream/rtc/play`, `${data.sipUser}/${data.videoChannelId}`)
                            } else {
                                window.layer.msg('暂无设备号/通道号')
                            }
                        }
                    })
            } else {
                gis.widgetObj.sullivan.close();
                window.layer.msg('未关联摄像头');
            }
        }
            break;
        case '合并列表': {
            const eventTime = this.pageObj.getApiWidgetsByClassName('event-time');
            const merge_modals = this.pageObj.getApiWidgetsByClassName('event-merge');
            merge_modals.forEach(v => v.hideWidget());
            eventTime.forEach(v => v.showWidget());

            this.pageObj.setVariables([{ name: 'event_parentId', value: data.id }])
        }
            break;
        case '合并': {
            const merge_modals = this.pageObj.getApiWidgetsByClassName('event-merge');
            const eventTime = this.pageObj.getApiWidgetsByClassName('event-time');
            merge_modals.forEach(v => v.showWidget());
            eventTime.forEach(v => v.hideWidget());
            // 暴露出事件id，合并事件时用
            window.mergeEventId = $event.params.data.id
            const table1 = this.getApiPage().getApiWidgetByAliasName('multiple-event');
            table1.widgetObj.table.checkrows = [{ id: $event.params.data.id, disabled: true }];
            table1.widgetObj.render();
        }
            break;
    }
}
